package navegar;

import java.io.*;

import lejos.nxt.*;
import lejos.nxt.comm.*;
import lejos.robotics.navigation.DifferentialPilot;
import lejos.util.Delay;

public class esclavo extends thread {
	static float obstaculo = 0;
	private static UltrasonicSensor sensor = new UltrasonicSensor(SensorPort.S2);
	static DifferentialPilot pilot = new DifferentialPilot(4f, 12f, Motor.A,
			Motor.C);
	static public DataOutputStream dos2;
	static public DataInputStream dis2;
	static int distMinima = 15;
	static int distSensada;
	static public esclavo esclavo;
	static int recibido=1;

	public static void main(String[] args) throws Exception {

		String connected = "Conectado";
		String waiting = "Esperando...";
		String closing = "Cerrando...";

		LCD.drawString(waiting, 0, 0);
		NXTConnection connection = Bluetooth.waitForConnection();
		LCD.clear();
		LCD.drawString(connected, 0, 0);

		DataInputStream dis2 = connection.openDataInputStream();
		DataOutputStream dos2 = connection.openDataOutputStream();

		while (obstaculo < 4) {

			LCD.clear();
			obstaculo = dis2.readFloat();
			System.out.print(obstaculo);
			Delay.msDelay(2000);	
			
			dos2.writeFloat(recibido);
			LCD.drawInt(recibido, 0, 3);
			dos2.flush();
			obstaculo=obstaculo+1;
			
			
		}

		dis2.close();
		dos2.close();

		LCD.clear();
		LCD.drawString(closing, 0, 0);

		connection.close();
		LCD.clear();
	}

	public void run() {
		// TODO Auto-generated method stub

		distSensada = sensor.getDistance();
		LCD.drawInt(distSensada, 4, 0, 3);

		if (distSensada < distMinima) {
			esclavo.evasion();
			try {
				dos2.writeFloat(obstaculo);
				dos2.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			obstaculo = obstaculo + 1;
		}
	}

	public void evasion() {

		LCD.drawString("'evadiendo'", 0, 7);
		Delay.msDelay(1000);
		pilot.travel(-30);
		pilot.rotate(25);
		LCD.drawString("'obstaculo'", 0, 8);
		Delay.msDelay(1000);
		LCD.clear();
	}

	
		
	}

